<template>
  <div>
    <transition-group name="swap" tag="div" class="list">
      <div
        v-for="(item, index) in items"
        :key="item"
        class="list-item"
        :style="{ order: index, height: item + 'px' }"
      >
        {{ item }}
      </div>
    </transition-group>
    <button @click="startBubbleSort" :disabled="isSorting">Start Bubble Sort</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: [150, 80, 200, 100, 50], // 初始数据
      isSorting: false,
      currentIndices: []
    };
  },
  methods: {
    async startBubbleSort() {
      if (this.isSorting) return;
      this.isSorting = true;

      let n = this.items.length;
      for (let i = 0; i < n - 1; i++) {
        for (let j = 0; j < n - i - 1; j++) {
          this.currentIndices = [j, j + 1];
          if (this.items[j] > this.items[j + 1]) {
            await this.swap(j, j + 1);
          }
          await this.sleep(100); // 延迟以显示动画
        }
      }
      this.currentIndices = [];
      this.isSorting = false;
    },
    swap(i, j) {
      return new Promise((resolve) => {
        [this.items[i], this.items[j]] = [this.items[j], this.items[i]];
        setTimeout(resolve, 500); // 与 CSS 动画时间匹配
      });
    },
    sleep(ms) {
      return new Promise(resolve => setTimeout(resolve, ms));
    }
  }
};
</script>

<style scoped>
.list {
  display: flex;
  flex-direction: column;
  width: 100px;
}

.list-item {
  width: 100px;
  background-color: blue;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ccc;
  box-sizing: border-box;
  transition: height 0.5s, transform 0.5s;
}

.swap-enter-active, .swap-leave-active {
  transition: transform 0.5s;
}

button {
  margin-top: 20px;
  padding: 10px 20px;
  font-size: 16px;
}
</style>